package org.zjvis.datascience.common.annotation;

import cn.hutool.core.util.EnumUtil;
import org.springframework.util.CollectionUtils;

import javax.validation.Constraint;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import javax.validation.Payload;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.util.List;

/**
 * @description 枚举类型字段校验鉴权注解
 * @date 2021-12-24
 */
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = EnumValue.Validator.class)
public @interface EnumValue {

    String message() default "枚举类型值不正确";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};

    Class<? extends Enum<?>> enumClass();

    /**
     * 默认校验value字段，即输入值需为该枚举类的checkField字段的值
     */
    String checkField() default "value";

    class Validator implements ConstraintValidator<EnumValue, Object> {

        private Class<? extends Enum<?>> enumClass;
        private String checkField;

        @Override
        public void initialize(EnumValue enumValue) {
            checkField = enumValue.checkField();
            enumClass = enumValue.enumClass();
        }

        @Override
        public boolean isValid(Object value, ConstraintValidatorContext constraintValidatorContext) {
            if (value == null) {
                return Boolean.TRUE;
            }

            if (enumClass == null) {
                return Boolean.TRUE;
            }
            List<Object> values = EnumUtil.getFieldValues(enumClass, checkField);
            if (CollectionUtils.isEmpty(values)) {
                return Boolean.FALSE;
            }
            return values.contains(value);
        }

    }
}
